package com.andaily.web.controller.mobile.account;

import com.andaily.domain.dto.account.AccountFormDTO;
import com.andaily.domain.dto.account.AccountTypeDTO;
import com.andaily.service.AccountService;
import com.andaily.web.controller.validator.AccountFormValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/account/form")
public class AccountFormController {

    private AccountService accountService;
    private AccountFormValidator accountFormValidator;

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(String guid, String date, String typeGuid, ModelMap model) {
        AccountFormDTO accountForm = accountService.loadAccountFormDTO(guid);
        accountForm.updateDate(date);
        accountForm.updateTypeGuid(typeGuid);
        List<AccountTypeDTO> accountTypes = accountService.loadAvailableAccountTypes();

        model.addAttribute("accountForm", accountForm);
        model.addAttribute("accountTypes", accountTypes);
        return "account/account_form";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String submit(@ModelAttribute("accountForm") AccountFormDTO accountForm, BindingResult result, ModelMap model) {
        accountFormValidator.validate(accountForm, result);
        if (result.hasErrors()) {
            return "account/account_form";
        }
        accountService.persistAccount(accountForm);
        //redirect
        String redirectUrl = (accountForm.isAddNext() ? "/m/account/form?date=" + accountForm.getAccountDate()
                + "&typeGuid=" + accountForm.getAccountType().getGuid()
                : "/m/account/overview");
        return "redirect:" + redirectUrl;
    }


    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @Autowired
    @Qualifier(value = "accountFormValidator")
    public void setAccountFormValidator(AccountFormValidator accountFormValidator) {
        this.accountFormValidator = accountFormValidator;
    }
}
